package org.jeecg.modules.inspect.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.inspect.entity.InsTask;
import org.jeecg.modules.inspect.mapper.InsTaskItemMapper;
import org.jeecg.modules.inspect.mapper.InsTaskMapper;
import org.jeecg.modules.inspect.service.IInsTaskService;
import org.jeecg.modules.inspect.util.SmsUtil;
import org.jeecg.modules.inspect.vo.DepartReportVo;
import org.jeecg.modules.inspect.vo.MonthReportVo;
import org.jeecg.modules.inspect.vo.RoleReportVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 任务
 * @Author: jeecg-boot
 * @Date:   2023-11-24
 * @Version: V1.0
 */
@Service
public class InsTaskServiceImpl extends ServiceImpl<InsTaskMapper, InsTask> implements IInsTaskService {

	@Resource
	private ISysBaseAPI sysBaseApi;

	@Resource
	private InsTaskMapper insTaskMapper;

	@Resource
	private InsTaskItemMapper insTaskItemMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		insTaskItemMapper.deleteByMainId(id);
		insTaskMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			insTaskItemMapper.deleteByMainId(id.toString());
			insTaskMapper.deleteById(id);
		}
	}

	@Override
	public List<InsTask> todoList(String departIds, String roleIds) {
		return insTaskMapper.todoList(departIds, roleIds);
	}
	@Override
	public List<InsTask> todoListByUserName(String userName) {
		List<InsTask> insTasks = insTaskMapper.todoListByUserName(userName);
		if(CollectionUtils.isNotEmpty(insTasks)){
			insTasks = insTasks.stream().filter(o-> StringUtils.isNotBlank(o.getUserId()) && Arrays.asList(o.getUserId().split(",")).contains(userName) ).collect(Collectors.toList());
		}
		return insTasks;
	}
	@Override
	public void taskTimeout() {
		List<InsTask> insTaskList = insTaskMapper.selectList(Wrappers.<InsTask>lambdaQuery()
				.ne(InsTask::getTaskStatus, "3")
				.lt(InsTask::getTaskEnd, DateUtil.now()));

		for(InsTask insTask : insTaskList) {
			// 4超时未检
			insTask.setTaskStatus("4");
			insTaskMapper.updateById(insTask);
		}
	}

	@Override
	public void taskRemind() {
		// 1待巡检 2巡检中 3已巡检 4超时未检
		List<InsTask> insTaskList = insTaskMapper.selectList(Wrappers.<InsTask>lambdaQuery()
				.ne(InsTask::getTaskStatus, "3")
				.eq(InsTask::getTaskEnd,
						DateUtil.format(DateUtil.offsetSecond(DateUtil.offsetHour(DateUtil.endOfDay(new Date()), 8), 1), "yyyy-MM-dd HH:mm:ss")
						));

		for(InsTask insTask : insTaskList) {
			String executeCycle = insTask.getExecuteCycle();

			String phones = "";

			if("6".equals(executeCycle)) {
				String deptId = insTask.getDeptId();
				// 部门下所有人员
				List<String> userNames = sysBaseApi.getUserByDeptId(deptId);
				if(CollUtil.isNotEmpty(userNames)) {
					List<String> sendPhones = new ArrayList<>();
					for(String userName : userNames) {
						LoginUser loginUser = sysBaseApi.getUserByName(userName);
						sendPhones.add(loginUser.getPhone());
					}
					if(CollUtil.isNotEmpty(sendPhones)) {
						phones = String.join(",", sendPhones.stream().map(String::valueOf).distinct().collect(Collectors.toList()));
					}

				}
			} else {
				String roleId = insTask.getRoleId();
				// 角色下所有人员
				List<String> userNames = sysBaseApi.getUserByRoleId(roleId);
				if(CollUtil.isNotEmpty(userNames)) {
					List<String> sendPhones = new ArrayList<>();
					for(String userName : userNames) {
						LoginUser loginUser = sysBaseApi.getUserByName(userName);
						sendPhones.add(loginUser.getPhone());
					}
					if(CollUtil.isNotEmpty(sendPhones)) {
						phones = String.join(",", sendPhones.stream().map(String::valueOf).distinct().collect(Collectors.toList()));
					}
				}
			}

			if(StrUtil.isNotEmpty(phones)) {
				System.out.println("发送短信提醒任务即将到期人员：" + phones);

				// 发送巡检即将到期短信提醒
				String smsContent = "您有走动式巡检任务未完成，截止日期" + DateUtil.format(insTask.getTaskEnd(), "yyyy-MM-dd HH:mm:ss") + "！";
				SmsUtil.sendMas(phones.split(","), smsContent);

				//try {
				//	Client client = Client.getInstance( );
				//	// 登录地址需另外提供
				//	boolean isLoggedin = client.login( "http://112.35.4.197:15000", "ypoa", "ypoadxfs", "永坪炼油厂" );
				//	if( isLoggedin ) {
				//		log.debug("发送短信登录成功");
				//	} else {
				//		log.debug("发送短信登录失败");
				//		client.login( "http://112.35.4.197:15000", "ypoa", "ypoadxfs", "永坪炼油厂" );
				//	}
				//
				//	// 普通短信:new String[]{ "18292100130" }
				//	int rt = client.sendDSMS(phones.split(",") , "您有走动式巡检任务未完成，截止日期" +
				//			DateUtil.format(insTask.getTaskEnd(), "yyyy-MM-dd HH:mm:ss") + "！", "123", 1, "hysyRh6yt", null, true );
				//	log.debug("发送短信返回值:" + rt + ",任务编号：" + insTask.getTaskNo());
				//
				//} catch (Exception e) {
				//	e.printStackTrace();
				//	log.error("发送短信出错" + e.getMessage());
				//}
			}
			// 发送短信结束

			/*
			// 所有人未巡检短信提醒
			String receiver = "admin";

			// 排班任务
			if("6".equals(executeCycle)) {
				String deptId = insTask.getDeptId();
				// 部门下所有人员
				List<String> userNames = sysBaseApi.getUserByDeptId(deptId);
				if(CollUtil.isNotEmpty(userNames)) {
					receiver = String.join(",", userNames.stream().map(String::valueOf).collect(Collectors.toList()));
					if(CollUtil.isNotEmpty(userNames)) {
						receiver = String.join(",", userNames.stream().map(String::valueOf).collect(Collectors.toList()));
					}
				}
			} else {
				String roleId = insTask.getRoleId();
				// 角色下所有人员
				List<String> userNames = sysBaseApi.getUserByRoleId(roleId);
				if(CollUtil.isNotEmpty(userNames)) {
					receiver = String.join(",", userNames.stream().map(String::valueOf).collect(Collectors.toList()));
				}
			}
			if(StrUtil.isNotEmpty(receiver)) {
				try {
					MessageDTO md = new MessageDTO();
					md.setFromUser("system");
					md.setToAll(false);
					md.setTitle("巡检任务提醒");
					md.setContent("您有巡检任务即将到期，请即时进行巡检！");
					//md.setTemplateCode(CommonSendStatus.INSPECT_TASK);
					md.setToUser(receiver);
					md.setType("system");
					Map<String, Object> data = new HashMap<>();
					data.put("taskName", insTask.getTaskName());
					data.put("taskBegin", DateUtil.format(insTask.getTaskBegin(), "yyyy-MM-dd HH:mm:ss"));
					data.put("taskEnd", DateUtil.format(insTask.getTaskEnd(), "yyyy-MM-dd HH:mm:ss"));

					md.setData(data);
					sysBaseApi.sendTemplateMessage(md);

				} catch (Exception e) {
					e.printStackTrace();
					log.error("发送消息出错" + e.getMessage());
				}
			}
			*/
		}
	}

	@Override
	public IPage<RoleReportVo> roleReport(Page<RoleReportVo> page, RoleReportVo roleReportVo) {

		return this.insTaskMapper.roleReport(page, roleReportVo);
	}

	@Override
	public IPage<DepartReportVo> departReport(Page<DepartReportVo> page, DepartReportVo departReportVo) {

		return this.insTaskMapper.departReport(page, departReportVo);
	}

	@Override
	public IPage<MonthReportVo> monthReport(Page<MonthReportVo> page, MonthReportVo monthReportVo) {

		return this.insTaskMapper.monthReport(page, monthReportVo);
	}

}
